from influxdb_client import InfluxDBClient
import pandas as pd
import json
import configparser

# 创建 ConfigParser 对象
config = configparser.ConfigParser()

# 读取配置文件
config.read('config.ini')


class InfluxDBDataFetcher:
    def __init__(self, url, token, org, bucket):
        self.client = InfluxDBClient(url=url, token=token, org=org)
        self.bucket = bucket

    def get_all_data(self):
        query = '''
        from(bucket: "wlh")
          |> range(start: 0)
          |> filter(fn: (r) => r["_measurement"] == "odds")
          |> filter(fn: (r) => r["_field"] == "odds")
          |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
          |> sort(columns: ["_time"], desc: false)
          |> yield(name: "all_data")
        '''
        result = self.client.query_api().query_data_frame(query)
        if result.empty:
            print("查询结果为空。")
            return pd.DataFrame()
        return result.drop(columns=["result", "table", "_start", "_stop", "_measurement"], errors='ignore')

    def get_odds_data(self, match_id):
        query = f'''
            from(bucket: "{self.bucket}")
              |> range(start: 0)
              |> filter(fn: (r) => r["_measurement"] == "odds")
              |> filter(fn: (r) => r["_field"] == "odds")
              |> filter(fn: (r) => r["team"] == "{match_id}" )
              |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
              |> sort(columns: ["_time"], desc: false)  // 按时间升序排序
              |> yield(name: "all_data")
            '''
    
        result = self.client.query_api().query_data_frame(query)
        if result.empty:
            print(f"查询结果为空，可能没有符合条件的数据（队伍: {match_id}）")
            return pd.DataFrame()  # 返回空的 DataFrame 以防报错
    
        # 删除不需要的列
        data = result.drop(columns=["result", "table", "_start", "_stop", "_measurement"], errors='ignore')
        # 将时间列设为索引
        data.set_index("_time", inplace=True)
            
        return data
    
    def generate_match_config(self, df):
        matches = []
    
        # 添加比赛ID列
        df['match_id'] = df['team'].apply(lambda x: '-'.join(x.split('-')[:2]))
        # print(df)
        # 处理数据
        grouped = df.groupby(['match_id'])
        
        
        for match_id, group in grouped:
            # print(group)
            teams = group['team'].unique()
            if len(teams) < 2 :
                continue
            elif len(teams) > 2 :
                print(teams)
                continue
            # print(teams,group,match_id)
            
            team1_id = teams[0]
            team2_id = teams[1]
            team1_data = self.get_odds_data(team1_id)
            team2_data = self.get_odds_data(team2_id)

            team1_last_row = team1_data.iloc[-1]
            team2_last_row = team2_data.iloc[-1]

            team1_odds = team1_last_row['odds']
            team2_odds = team2_last_row['odds']
            # print(team1_last_row)
            # print(team2_last_row)
            # 确保有两个队伍信息
            
            # 确定胜负
            if team1_odds > team2_odds:
                match_label = 'team1'
            elif team2_odds > team1_odds:
                match_label = 'team2'
            else:
                match_label = 'unknown'  # 如果赔率相同，则标记为未知
    
            if match_label != 'unknown' :
                matches.append({
                    'team1_id': team1_id,
                    'team2_id': team2_id,
                    'match_label': match_label
                })
    
        return matches


def main():
    # InfluxDB 配置
    url = config['influxdb']['url']
    token = config['influxdb']['token']
    org = config['influxdb']['org']
    bucket = config['influxdb']['bucket']

    fetcher = InfluxDBDataFetcher(url, token, org, bucket)
    df = fetcher.get_all_data()

    if df.empty:
        print("没有数据可供处理。")
        return

    # 生成比赛配置
    matches = fetcher.generate_match_config(df)

    # 将配置保存为 JSON 文件
    with open('matches_config.json', 'w') as f:
        json.dump(matches, f,  indent=4, ensure_ascii=False)

    print("比赛配置已生成并保存为 matches_config.json")


if __name__ == "__main__":
    main()
